<?php
/**
  * wechat php test
  */

// define your token
define("TOKEN", "myproject");
$wechatObj = new wechatCallbackapiTest();
// $wechatObj->valid();
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		// $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; // php5.6之前用于获取原始的post数据
        $postStr = file_get_contents("php://input"); // php5.6之后用于获取原始的post数据

      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                // 回复文本消息
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>"; 
                                        
				if(!empty( $keyword ))  // 普通消息
                {
                // 关键词搜索，从记录位置的文件中读取位置信息
                    $path = "./location/$fromUsername";
                    if (file_exists($path)) {
                        $location = json_decode(file_get_contents($path), true);
                        $jd = $location['jd'];
                        $wd = $location['wd'];
                        $ak = "EIbXH3wccPBS80cUPDYA4tGZmw37xAZa";
                        $url = "http://api.map.baidu.com/telematics/v3/local?location={$jd},{$wd}&keyWord={$keyword}&output=json&ak={$ak}&number=3";
                        
                        $res = file_get_contents($url);
                        $res = json_decode($res,true);
                        $str = '';
                        if ( ($num = count($res['pointList'])) != 0 ) {
                            foreach($res['pointList'] as $v) {
                                $str .= "{$v['name']},位于{$v['address']},距离您{$v['distance']}米\n\n";
                            }
                            $str = "最近的{$num}个{$keyword}:".$str;
                        } else {
                            $str = "没有找到任何{$keyword}.";
                        }

                        $msgType = "text";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $str);
                        echo $resultStr;
                    } 
                    //else {
                        // $str = '请发送您的地理位置!';
                        // $msgType = "text";
                        // $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $str);
                        // echo $resultStr;
                    //}


              		$msgType = "text";
                    $contentStr = "欢迎进入我的微信公众号";
                    if ($keyword == "帅哥") {
                        $contentStr = "哥除了帅，其他啥都没有！";
                    }
                    if ($keyword == "美女") {
                        $contentStr = "美中不足，是缺憾";
                    }
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                } elseif ($postObj->MsgType == 'event') {  // 关注事件
                    if ($postObj->Event == 'CLICK') {
                        $contentStr = "发送自己的地里定位，就可以开启关键词搜索喽!如输入：‘酒店’，返回最近的酒店信息";
                        $msgType = "text";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                    } else
                    if ($postObj->Event == 'subscribe') {  // subscibe 订阅 unsubscribe取消订阅
                        $contentStr = "欢迎关注我的微信公众号!";
                        $msgType = "text";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                    } elseif ($postObj->Event ==  'LOCATION') {  // 文件方式保存位置信息 上报地理位置
                        $arr['jd'] = "$postObj->Longitude";
                        $arr['wd'] = "$postObj->Latitude";
                        $arr['time'] = time();
                        $str = json_encode($arr);
                        file_put_contents("./location/$fromUsername", $str);
                    }
                } elseif ($postObj->MsgType == "location") {  // 地理位置 
                    $jd = $postObj->Location_Y;
                    $wd = $postObj->Location_X;
                    $linfo = $postObj->Label;

                // 文件方式保存位置信息
                    $arr['jd'] = "$jd";
                    $arr['wd'] = "$wd";
                    $arr['time'] = time();
                    $str = json_encode($arr);
                    file_put_contents("./location/$fromUsername", $str);

                    $msgType = "text";
                    $contentStr = "已收到您的位置信息,输入您要搜索内容的关键词.";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;

                // 找厕所
                    /*$key = "厕所";
                    $keyword = urlencode($key);
                    $ak = "EIbXH3wccPBS80cUPDYA4tGZmw37xAZa";
                    $url = "http://api.map.baidu.com/telematics/v3/local?location={$jd},{$wd}&keyWord={$keyword}&output=json&ak={$ak}&number=3";
                    
                    $res = file_get_contents($url);
                    $res = json_decode($res,true);
                    $str = '';
                    if ( ($num = count($res['pointList'])) != 0 ) {
                        foreach($res['pointList'] as $v) {
                            $str .= "{$v['name']},位于{$v['address']},距离您{$v['distance']}米\n\n";
                        }
                        $str = "3公里内共找到{$num}个{$key}:".$str;
                    } else {
                        $str = "没有找到任何{$key}.";
                    }

                    $msgType = "text";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $str);
                    echo $resultStr;*/

                // 回复位置信息
                    /*$msgType = "text";
                    $contentStr = "我的位置：东经$jd,北纬$wd,地名$linfo";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;*/
                }elseif ($postObj->MsgType == "image") {  // 图片消息
                    //音乐回复
                    $musicTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Music>
                    <Title><![CDATA[%s]]></Title>
                    <Description><![CDATA[%s]]></Description>
                    <MusicUrl><![CDATA[%s]]></MusicUrl>
                    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                    </Music>
                    </xml>";

                    $msgType = "music";
                    $title = "音乐";
                    $des = "音乐回复";
                    $URL = "http://wx0902.ittun.com/music.mp3";
                    $HQURL = "http://wx0902.ittun.com/hmusic.mp3";
                    $resultStr = sprintf($musicTpl, $fromUsername, $toUsername, $time, $msgType, $title, $des, $URL, $HURL);
                    echo $resultStr;

                    // $msgType = "text";
                    // $contentStr = "lallla!";
                    // $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    // echo $resultStr;
                }
                else{
                    echo "Input something...";
                }   
        }else {
        	echo "";
        	exit;
        }
    }
		
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}